import { useEffect, useState } from 'react';
import { NavBar, Space, Toast } from 'antd-mobile'
import { useNavigate, useParams } from 'react-router-dom'
import { API_BASE, dishDetail, likeDish, collectDish } from "./service";
import Card from './Card';

import { Steps } from 'react-vant';
import { Image } from 'react-vant';
import { Button } from 'react-vant'
import { Plus } from '@react-vant/icons'

export default function () {
  const navigate = useNavigate();
  const { dishId } = useParams();
  const [wait, setWait] = useState(false);
  const [dish, setDish] = useState();

  useEffect(() => {
    (async () => {
      let { data } = await dishDetail(dishId);
      console.log(data?.data)
      setDish(data?.data)
    })()
  }, [])

  const handleLike = state => async (id) => {
    if (wait) {
      return
    }
    try {
      setWait(true);
      await likeDish({ dishesId: id, newState: !state }).then(() => {
        if (!dish.myLikeState) {
          dish.likeCount += 1;
          dish.myLikeState = true;
        } else {
          dish.likeCount -= 1;
          dish.myLikeState = false;
        }
        setDish(dish)
      });
    } catch (e) {
      console.error(e)
    }
    finally {
      setWait(false)
    }
  }
  const handleCollect = state => async (id) => {
    if (wait) {
      return
    }
    setWait(true);
    try {
      await collectDish({ dishesId: id, newState: !state }).then(() => {
        if (!dish.myCollectionState) {
          dish.collectionCount += 1;
          dish.myCollectionState = true;
        } else {
          dish.collectionCount -= 1;
          dish.myCollectionState = false;
        }
        setDish(dish)
      });
    } catch (e) {
      console.error(e)
    } finally {
      setWait(false)
    }
  }

  return (
    <div >
      <NavBar onBack={() => { navigate(-1) }}>菜品详情</NavBar>
      <Card
        dish={dish}
        onCollect={handleCollect(dish?.myCollectionState)}
        onLike={handleLike(dish?.myLikeState)}
      />


      {dish && (<div style={{
        display: "flex",
        alignItems: "center",
        padding: "12px"
      }}>
        <Image round width={40} height={40} src={`${API_BASE}${dish.author.avatar}`} />
        <div style={{ fontSize: "18px", marginLeft: "12px" }}>{dish.author.name}</div>
        <Button icon={<Plus />} style={{ marginLeft: "auto" }} iconPosition='left' type='primary' size='small'>关注
        </Button>
      </div>)}

      <Steps direction="vertical" active={-1}>
        {
          dish?.stepList?.map((item, idx) => {
            return <Steps.Item key={idx} >
              <h3 style={{ marginBottom: "12px" }}>{item.content}</h3>
              <Image src={`${API_BASE}${item.imgUrl}`} />
            </Steps.Item>
          })
        }
      </Steps>
    </div>
  )
}